package com.jeeplus.modules.api.wxpay;

import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @Date: 2018/8/10 20:59
 * @Description: test
 */
public class WxTx {

    @Autowired
    HttpServletRequest request;
    private static final String mchId = "1537918971";
    private static final String mchSecret = "Zhuanjiazixunxiaochengxu20211233";
    private static final String appId = "wx51e55422ec004931";
    private final SortedMap<String, String> sortedMap = new TreeMap<>();

//    public static void main(String[] args) throws Exception {
//        WxtxTest wt = new WxtxTest();
//        String openid = "o-SxH4zY7RcKab9bHZ9NXjQ56RFI";
//        Integer amount=(new BigDecimal(1).multiply(new BigDecimal(100))).intValue();
//        String sginCode = wt.getSgin(openid, amount);//获取用户openid 和 用户要提现的金额  拿到签名
//        EnterprisesPayment enterprisesPayment = wt.addEnterprisesPayment(openid, sginCode,amount);//拿到签名后加密得到要发送到对象数据
//        String enterprisesPaymentXML = WeixinpayUtil.createDocumentForEnterprisesPayment(enterprisesPayment,amount);  //封装xml 数据发送
//        String returnXmlData = ClientCustomSSL.doRefund("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers", enterprisesPaymentXML);
//        Map<String, String> resultMap = OtherUtils.readStringXmlOut(returnXmlData);
//
//        if (resultMap.containsKey("result_code") && "SUCCESS".equals(resultMap.getOrDefault("result_code", ""))) {
//            System.out.println("提现成功");
//            System.out.println("返回结果：" + returnXmlData);
//        } else {
//            System.out.println("提现成功");
//            System.out.println("返回结果：" + returnXmlData);
//        }
//        System.out.println(returnXmlData);
//    }

//    public static String weChatTx(String openid, Integer amount) throws Exception {
//        WxtxTest wt=new WxtxTest();
//        String sginCode = wt.getSgin(openid,amount);//获取用户openid 和 用户要提现的金额  拿到签名
//        amount=(new BigDecimal(amount).multiply(new BigDecimal(100))).intValue();
//        EnterprisesPayment enterprisesPayment  = wt.addEnterprisesPayment(openid,sginCode,amount);//拿到签名后加密得到要发送到对象数据
//        String enterprisesPaymentXML = WeixinpayUtil.createDocumentForEnterprisesPayment(enterprisesPayment,amount);  //封装xml 数据发送
//        String returnXmlData =ClientCustomSSL.doRefund("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers",enterprisesPaymentXML);
//        Map<String,String> resultMap = OtherUtils.readStringXmlOut(returnXmlData);
//
//        if(resultMap.containsKey("result_code") && "SUCCESS".equals(resultMap.getOrDefault("result_code",""))){
//            System.out.println("提现成功");
//            System.out.println("返回结果："+returnXmlData);
//        }else{
//            System.out.println("提现成功");
//            System.out.println("返回结果："+returnXmlData);
//        }
//        return returnXmlData;
//    }

    public EnterprisesPayment addEnterprisesPayment(String openid, String sginCode,Integer amount) {
        EnterprisesPayment enterprisesPayment = new EnterprisesPayment();
        enterprisesPayment.setMch_appid(appId);//商户号appid
        enterprisesPayment.setMchid(mchId);//商户号 
        System.out.println("nonce_str:" + sortedMap.get("nonce_str"));
        enterprisesPayment.setNonce_str(sortedMap.get("nonce_str"));//随机字符串 
        enterprisesPayment.setSign(sginCode);//签名 
        System.out.println("nonce_str:" + sortedMap.get("partner_trade_no"));
        enterprisesPayment.setPartner_trade_no(sortedMap.get("partner_trade_no"));//商户订单号 
        enterprisesPayment.setOpenid(openid);
        enterprisesPayment.setCheck_name(sortedMap.get("check_name"));
        enterprisesPayment.setAmount(amount);//金额 
        enterprisesPayment.setDesc(sortedMap.get("desc"));//描述 
        enterprisesPayment.setSpbill_create_ip(sortedMap.get("spbill_create_ip"));//ip地址 
        return enterprisesPayment;
    }

    public String getSgin(String openid, Integer amount, String info) throws UnsupportedEncodingException {
        //HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        sortedMap.put("mch_appid", appId);
        sortedMap.put("mchid", mchId);
        sortedMap.put("nonce_str", WXPayUtil.getUUID());
        sortedMap.put("partner_trade_no", WXPayUtil.getOrderId());
        sortedMap.put("openid", openid);
        sortedMap.put("check_name", "NO_CHECK");
        sortedMap.put("amount", String.valueOf(amount));
        sortedMap.put("desc", info);
        //ip地址
        String spbill_create_ip = IpUtil.getIpAddr(request);
        sortedMap.put("spbill_create_ip", "123.149.215.158");
        System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
        System.out.println(sortedMap.toString());
        System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
        return WXPayUtil.getSignCode(sortedMap,mchSecret);
        //return createSign(sortedMap, mchSecret);
    }

    /**
     * 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
     */
    public static String createSign(SortedMap<String, String> packageParams, String AppKey) {
        StringBuffer sb = new StringBuffer();
        Set es = packageParams.entrySet();
        System.out.println(es);
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + AppKey);
        String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
        return sign;
    }
}
